package com.cw.demo.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 * TODO
 *
 * @author chenw
 * @date 2021/10/9
 */
public class Task implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        Thread.sleep(2000);
        return 2;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Task task = new Task();
        ExecutorService executorService = Executors.newCachedThreadPool();
        Future<Integer> future = executorService.submit(task);
        //在高并发环境下，有可能Callable和FutureTask会创建多次，FutureTask能够确保在高并发环境下任务只执行一次。
        FutureTask<Integer> futureTask = new FutureTask<>(task);
        System.out.println(future.isDone());
        System.out.println(future.get());
        System.out.println(future.isDone());
        executorService.shutdown();
    }
}
